﻿
using MongoDB.Bson.IO;
using MongoDB.Driver.Core.Events;
using PacketDotNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;

namespace HBase {
    public class MyTcpClient {
        public bool isCloss = false;
        Socket client = null;
        public DateTime lastUse;
        protected List<TcpData> all = new List<TcpData>();
        public MyTcpClient() {
            lastUse = DateTime.Now;
        }

        public void fill(Socket client) {
            this.client = client;
            System.Threading.Tasks.Task.Factory.StartNew(() => {
                run();
            });
        }


        void run() {
            try {
                doRead();
            } catch {
                LoggerCommon.fileAll(1, "客户端断开链接" + client.RemoteEndPoint.ToString());
            } finally {

                close();
            }

        }
        public void close() {
            isCloss = true;
            try {
                client.Close();
            } catch {

            }


        }

        void doRead() {
            while (true) {
                //接收客户端的消息
                byte[] data = new byte[4096];//定义缓存区
                int length = client.Receive(data);//信息的有效长度
                if (!client.Connected) {
                    break;
                }
                if (length == 0) {
                    client.Send(new byte[] { 1 });
                    continue;
                }
                lastUse = DateTime.Now;
                byte[] d = getData(data, length);
                if (readed(d)) {
                    all.Add(new TcpData(d));
                }
                removeDelete();
            }

        }


        byte[] getData(byte[] data, int len) {
            byte[] d = new byte[len];
            for (int i = 0; i < len; i++) {
                d[i] = data[i];
            }
            return d;
        }
        void removeDelete() {
            for (int i = 0; i < all.Count; i++) {
                if (all[i].delete) {
                    all.RemoveAt(i);
                    i--;
                }
            }
        }
        public virtual bool readed(byte[] b) {
            return false;
        }

        public void send(byte[] d) {
            if (client.Connected) {
                client.Send(d);
            }

        }

    }
    public class TcpData {
        public TcpData(byte[] d) {
            data = d;
        }
        public bool delete = false;
        public byte[] data;

    }

}